package com.wy.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("fileBase64Down")
@CrossOrigin("*")
public class Base64DownController {

    @GetMapping("/download")
    @ResponseBody
    public ResponseEntity<Map<String, String>> downloadFile(String fileName) {
        // 1. 根据文件名获取文件（这里假设文件存储在某个目录中）
        System.out.println("filename =" + fileName);
        File file = new File("C:\\Users\\Administrator\\Desktop\\archivebug.txt");
        HashMap<String, String> res = new HashMap<>();
        if (!file.exists()) {
            res.put("error", "文件不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(res);
        }
        // 2. 将文件转换为Base64编码
        String base64;
        try {
            byte[] fileContent = Files.readAllBytes(file.toPath());
            base64 = Base64.getEncoder().encodeToString(fileContent);
        } catch (IOException e) {

            res.put("error", "文件读取失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(res);
        }
        res.put("fileName", fileName);
        res.put("base64", base64);
        // 3. 返回Base64数据和文件名
        return ResponseEntity.ok(res);
    }
}